/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.deservel.wxopen.test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author DeserveL
 * @date 2017/7/12 18:03
 * @since 1.0.0
 */
public class ChatClient {
    private String host = "localhost";// 默认连接到本机
    private int port = 8189;// 默认连接到端口8189

    public ChatClient() {

    }

    // 连接到指定的主机和端口
    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void chat() {
        try {
            // 连接到服务器
            Socket socket = new Socket(host, port);

            try {
                // 读取服务器端传过来信息的DataInputStream
                DataInputStream in = new DataInputStream(socket
                        .getInputStream());
                // 向服务器端发送信息的DataOutputStream
                DataOutputStream out = new DataOutputStream(socket
                        .getOutputStream());

                // 装饰标准输入流，用于从控制台输入
                Scanner scanner = new Scanner(System.in);
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        while(true){
                            String send = scanner.nextLine();
                            try {
                                out.writeUTF("客户端：" + send);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                thread.start();
                while (true) {
//                    String send = scanner.nextLine();
//                    System.out.println("客户端：" + send);
//                    // 把从控制台得到的信息传送给服务器
//                    out.writeUTF("客户端：" + send);
                    // 读取来自服务器的信息
                    String accpet = in.readUTF();
                    System.out.println(accpet);
                }

            } finally {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ChatClient().chat();
    }
}
